<template>
  <view class="coupon-container">
    <!-- 导航栏 -->
    <u-navbar title="我的优惠券" :border-bottom="false" :background="{ background: themeColorStyles.primaryColor }" title-color="#FFFFFF">
      <view class="u-nav-slot" slot="left">
        <u-icon name="arrow-left" color="#FFFFFF" size="20" @click="$u.route('/pages/mine/index')"></u-icon>
      </view>
      <view class="u-nav-slot" slot="right">
        <view class="cache-info" :style="{background: themeColorStyles.cacheInfoBg, border: themeColorStyles.cacheInfoBorder}" @click="showCacheStatus">
          <text class="cache-text">缓存</text>
        </view>
      </view>
    </u-navbar>

    <!-- 状态筛选 -->
    <view class="filter-tabs">
      <view 
        class="tab-item" 
        :class="{ active: currentTab === item.value }"
        :style="currentTab === item.value ? {color: themeColorStyles.primaryColor} : {}"
        v-for="item in tabList" 
        :key="item.value"
        @click="switchTab(item.value)"
      >
        {{ item.label }}
        <view v-if="currentTab === item.value" class="tab-indicator" :style="{background: themeColorStyles.primaryColor}"></view>
      </view>
    </view>

    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <view v-if="loading" class="loading-container">
        <u-loading-icon mode="flower"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else-if="couponList.length === 0" class="empty-container">
        <image src="/static/images/empty/coupon.png" class="empty-image"></image>
        <text class="empty-text">暂无优惠券</text>
      </view>
      
      <view v-else>
        <view 
          class="coupon-item" 
          v-for="coupon in couponList" 
          :key="coupon.userCouponId"
          @click="viewCouponDetail(coupon)"
        >
          <view class="coupon-left" 
                :class="getCouponStatusClass(coupon.useStatus || coupon.use_status)"
                :style="getCouponLeftStyle(coupon.useStatus || coupon.use_status)">
            <view class="coupon-amount">
              <text class="currency" v-if="coupon.couponType !== '2'">¥</text>
              <text class="amount">{{ getCouponAmountDisplay(coupon) }}</text>
              <text class="discount-suffix" v-if="coupon.couponType === '2'">折</text>
            </view>
            <view class="coupon-condition">{{ getCouponCondition(coupon) }}</view>
          </view>
          
          <view class="coupon-right">
            <view class="coupon-title">{{ coupon.couponName || '优惠券' }}</view>
            <view class="coupon-desc">{{ coupon.remark || getCouponTypeText(coupon.couponType) }}</view>
            <view class="coupon-time">
              有效期至：{{ formatDate(coupon.expireTime) }}
            </view>
            <view class="coupon-bottom">
              <view class="coupon-status">
                <text class="status-text" 
                      :class="getCouponStatusClass(coupon.useStatus || coupon.use_status)"
                      :style="getCouponStatusStyle(coupon.useStatus || coupon.use_status)">
                  {{ getCouponStatusText(coupon.useStatus || coupon.use_status) }}
                </text>
              </view>
              <!-- 线下核销按钮 -->
              <view v-if="coupon.useStatus === '0' || coupon.use_status === '0'" class="offline-verify-btn" 
                    :style="{background: themeColorStyles.primaryColor}"
                    @click.stop="showOfflineVerifyModal(coupon)">
                <text class="verify-btn-text">线下核销</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore && !loading" class="load-more" @click="loadMore">
      <text class="load-more-text" :style="{color: themeColorStyles.primaryColor}">加载更多</text>
    </view>

    <!-- 线下核销二维码弹窗 -->
    <view v-if="showQRModal" class="qr-modal-overlay" @click="closeQRModal">
      <view class="qr-modal-content" @click.stop>
        <view class="qr-modal-header">
          <text class="qr-modal-title">线下核销二维码</text>
          <view class="qr-modal-close" @click="closeQRModal">
            <text class="close-icon">×</text>
          </view>
        </view>
        
        <view class="qr-modal-body">
          <view class="coupon-info-card">
            <view class="coupon-name">{{ currentCoupon?.couponName || '优惠券' }}</view>
            <view class="coupon-amount-display">
              <text class="currency" v-if="currentCoupon?.couponType !== '1'">¥</text>
              <text class="amount">{{ getCouponAmountDisplay(currentCoupon) }}</text>
              <text class="discount-suffix" v-if="currentCoupon?.couponType === '1'">折</text>
            </view>
            <view class="coupon-condition-text">{{ getCouponCondition(currentCoupon) }}</view>
          </view>
          
          <view class="qr-code-container">
            <canvas v-if="useCanvas" canvas-id="qrcode-canvas" class="qr-canvas"></canvas>
            <image v-else :src="qrCodeUrl" class="qr-code-image" mode="aspectFit"></image>
          </view>
          
          <view class="qr-code-text">
            <text class="qr-text-label">核销码：</text>
            <text class="qr-text-value">{{ qrCodeText }}</text>
          </view>
          
          <view class="qr-tips">
            <text class="tips-text">请将此二维码出示给商家进行核销</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserCouponList } from '@/api/coupon'
import { handleApiError } from '@/utils/errorHandler'
import couponCache from '@/utils/couponCache'
import { API_CONFIG } from '@/api/config.js'
import { getThemePrimaryColor } from '@/utils/themeUtils'
import { generateCouponQRCode } from '@/utils/qrcodeUtils'

export default {
  data() {
    return {
      loading: false,
      currentTab: 'all',
      couponList: [],
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      userId: null,
      primaryColor: '#4A90E2',
      tabList: [
        { label: '全部', value: 'all' },
        { label: '未使用', value: '0' },
        { label: '已使用', value: '1' },
        { label: '已过期', value: '2' }
      ],
      // 二维码弹窗相关
      showQRModal: false,
      currentCoupon: null,
      qrCodeUrl: '',
      qrCodeText: '',
      useCanvas: false // 是否使用Canvas生成二维码
    }
  },
  
  onLoad() {
    // 获取用户ID
    const userInfo = uni.getStorageSync('userInfo')
    this.userId = userInfo ? userInfo.user.userId : null
    this.initThemeColor()
    this.loadCouponList()
  },
  
  computed: {
    themeColorStyles() {
      return this.setThemeColorVariables(this.primaryColor)
    }
  },
  
  onShow() {
    // 页面显示时刷新数据
    this.refreshData()
  },
  
  onPullDownRefresh() {
    this.refreshData()
  },
  
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  
  methods: {
    // 初始化主题色
    async initThemeColor() {
      try {
        // 获取主题色配置
        const themeColor = await getThemeColorFromGlobal()
        
        // 判断是否为异步主题色（数字字符串表示需要从服务器获取）
        if (/^\d+$/.test(themeColor)) {
          // 异步获取主题色
          this.primaryColor = getThemePrimaryColor(themeColor)
          console.log('异步获取主题色 - 优惠券列表页面:', themeColor)
        } else {
          // 同步获取主题色（直接使用颜色值）
          this.primaryColor = getThemePrimaryColor(themeColor)
          console.log('同步获取主题色 - 优惠券列表页面:', themeColor)
        }
      } catch (error) {
        console.error('优惠券列表页面主题色初始化失败:', error)
        // 使用默认主题色
        this.primaryColor = getThemePrimaryColor('1')
      }
    },
    
    // 设置主题色变量
    setThemeColorVariables(color) {
      const rgb = this.hexToRgb(color)
      
      return {
        primaryColor: color,
        cacheInfoBg: `rgba(255, 255, 255, 0.2)`,
        cacheInfoBorder: `1rpx solid rgba(255, 255, 255, 0.3)`,
        couponAvailableBg: `linear-gradient(135deg, ${color} 0%, ${this.darkenColor(color, 0.1)} 100%)`,
        statusAvailableBg: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        statusAvailableBorder: color
      }
    },
    
    // 十六进制颜色转RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : { r: 74, g: 144, b: 226 }
    },
    
    // 颜色变深
    darkenColor(color, amount) {
      const rgb = this.hexToRgb(color)
      const r = Math.max(0, Math.round(rgb.r * (1 - amount)))
      const g = Math.max(0, Math.round(rgb.g * (1 - amount)))
      const b = Math.max(0, Math.round(rgb.b * (1 - amount)))
      return `rgb(${r}, ${g}, ${b})`
    },
    
    // 获取优惠券左侧样式
    getCouponLeftStyle(status) {
      if (status === '0') {
        return { background: this.themeColorStyles.couponAvailableBg }
      }
      return {}
    },
    
    // 获取优惠券状态样式
    getCouponStatusStyle(status) {
      if (status === '0') {
        return {
          color: this.themeColorStyles.primaryColor,
          borderColor: this.themeColorStyles.statusAvailableBorder,
          background: this.themeColorStyles.statusAvailableBg
        }
      }
      return {}
    },
    
    // 切换标签
    switchTab(tab) {
      if (this.currentTab === tab) return
      this.currentTab = tab
      this.refreshData()
    },
    
    // 刷新数据
    refreshData() {
      this.pageNum = 1
      this.hasMore = true
      this.couponList = []
      this.loadCouponList(true) // 强制刷新，不使用缓存
    },
    
    // 加载优惠券列表
    async loadCouponList(forceRefresh = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        // 如果是第一页且不是强制刷新，尝试从缓存获取数据
        if (this.pageNum === 1 && !forceRefresh && this.userId) {
          const cachedData = couponCache.getCouponCache(this.currentTab, API_CONFIG.ORG_ID, this.userId)
          if (cachedData && cachedData.length > 0) {
            console.log('使用缓存的优惠券数据:', cachedData.length, '条')
            this.couponList = cachedData
            this.hasMore = cachedData.length === this.pageSize
            this.loading = false
            return
          }
        }
        
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        
        if (this.currentTab !== 'all') {
          params.status = this.currentTab
        }
        
        const response = await getUserCouponList(params)
        
        if (response.code === 200) {
          const newList = response.rows || []
          
          // 调试：打印优惠券数据结构
          if (newList.length > 0) {
            console.log('优惠券数据示例:', JSON.stringify(newList[0], null, 2))
            console.log('优惠券字段:', Object.keys(newList[0]))
            console.log('useStatus值:', newList[0].useStatus, '类型:', typeof newList[0].useStatus)
            console.log('use_status值:', newList[0].use_status, '类型:', typeof newList[0].use_status)
          }
          
          if (this.pageNum === 1) {
            this.couponList = newList
            // 缓存第一页数据
            if (this.userId && newList.length > 0) {
              couponCache.setCouponCache(this.currentTab, newList, API_CONFIG.ORG_ID, this.userId)
            }
          } else {
            this.couponList = [...this.couponList, ...newList]
          }
          
          this.hasMore = newList.length === this.pageSize
        } else {
          handleApiError(response)
        }
      } catch (error) {
        console.error('加载优惠券列表失败:', error)
        handleApiError(error)
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    // 加载更多
    loadMore() {
      this.pageNum++
      this.loadCouponList()
    },
    
    // 查看优惠券详情
    viewCouponDetail(coupon) {
      // 可以跳转到优惠券详情页面或显示详情弹窗
      let amountText = ''
      if (coupon.couponType === '2') {
        // 折扣券：不显示人民币符号
        amountText = `${this.getCouponAmountDisplay(coupon)}折`
      } else {
        // 满减券和无门槛券：显示人民币符号
        amountText = `¥${this.getCouponAmountDisplay(coupon)}`
      }
      
      uni.showModal({
        title: coupon.couponName || '优惠券详情',
        content: `优惠内容：${amountText}
使用条件：${this.getCouponCondition(coupon)}
有效期至：${this.formatDate(coupon.expireTime)}`,
        showCancel: false
      })
    },
    
    // 获取优惠券金额显示
    getCouponAmountDisplay(coupon) {
      if (coupon.couponType === '2') {
        // 折扣券：显示折扣率*10
        return (parseFloat(coupon.discountRate || 0.9) * 10) || '9'
      } else {
        // 满减券和无门槛券：显示优惠金额
        return coupon.couponAmount || '0'
      }
    },
    
    // 获取优惠券类型文本
    getCouponTypeText(couponType) {
      const typeMap = {
        '1': '满减券',
        '2': '折扣券', 
        '3': '无门槛券'
      }
      return typeMap[couponType] || '优惠券'
    },
    
    // 获取优惠券使用条件
    getCouponCondition(coupon) {
      if (coupon.couponType === '1' && coupon.minAmount && coupon.minAmount > 0) {
        // 满减券
        return `满${coupon.minAmount}元可用`
      } else if (coupon.couponType === '2' && coupon.minAmount && coupon.minAmount > 0) {
        // 折扣券
        return `满${coupon.minAmount}元可用`
      } else {
        // 无门槛券
        return '无门槛'
      }
    },
    
    // 获取优惠券状态文本
    getCouponStatusText(status) {
      const statusMap = {
        '0': '未使用',
        '1': '已使用',
        '2': '已过期'
      }
      return statusMap[status] || '未知状态'
    },
    
    // 获取优惠券状态样式类
    getCouponStatusClass(status) {
      const classMap = {
        '0': 'available',
        '1': 'used',
        '2': 'expired'
      }
      return classMap[status] || 'available'
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    
    // 显示缓存状态
    showCacheStatus() {
      if (!this.userId) {
        uni.showToast({ title: '用户未登录', icon: 'none' })
        return
      }
      
      const status = couponCache.getCacheStatus(API_CONFIG.ORG_ID, this.userId)
      let message = '优惠券缓存状态:\n'
      
      const statusLabels = {
        'all': '全部',
        '0': '未使用',
        '1': '已使用',
        '2': '已过期'
      }
      
      Object.keys(status).forEach(type => {
        const info = status[type]
        const label = statusLabels[type] || type
        message += `${label}: ${info.valid ? '有效' : '无效'} (${info.count}条)\n`
        if (info.timestamp) {
          message += `更新时间: ${info.timestamp}\n`
        }
      })
      
      uni.showModal({
        title: '缓存状态',
        content: message,
        showCancel: true,
        cancelText: '关闭',
        confirmText: '清除缓存',
        success: (res) => {
          if (res.confirm) {
            this.clearCache()
          }
        }
      })
    },
    
    // 清除缓存
    clearCache() {
      if (!this.userId) {
        uni.showToast({ title: '用户未登录', icon: 'none' })
        return
      }
      
      couponCache.clearAllCouponCache(API_CONFIG.ORG_ID, this.userId)
      this.couponList = []
      uni.showToast({ title: '缓存已清除', icon: 'success' })
    },

    // 显示线下核销二维码弹窗
    showOfflineVerifyModal(coupon) {
      console.log('显示线下核销二维码:', coupon)
      
      if (!coupon || (coupon.useStatus !== '0' && coupon.use_status !== '0')) {
        uni.showToast({ title: '该优惠券不可核销', icon: 'none' })
        return
      }
      
      this.currentCoupon = coupon
      this.generateQRCodeForCoupon(coupon)
      this.showQRModal = true
    },

    // 生成优惠券二维码
    generateQRCodeForCoupon(coupon) {
      try {
        // 生成二维码文本：优惠券码_优惠券ID
        const couponCode = coupon.couponCode || `CPN${coupon.userCouponId}`
        const couponId = coupon.userCouponId || coupon.couponId
        
        this.qrCodeText = `${couponCode}_${couponId}`
        
        // 使用在线服务生成二维码（备用方案）
        const encodedText = encodeURIComponent(this.qrCodeText)
        this.qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodedText}&format=png&margin=20`
        
        console.log('生成二维码:', this.qrCodeText)
        console.log('二维码URL:', this.qrCodeUrl)
        
      } catch (error) {
        console.error('生成二维码失败:', error)
        uni.showToast({ title: '生成二维码失败', icon: 'none' })
      }
    },

    // 关闭二维码弹窗
    closeQRModal() {
      this.showQRModal = false
      this.currentCoupon = null
      this.qrCodeUrl = ''
      this.qrCodeText = ''
    }
  }
}
</script>

<style scoped>
.coupon-container {
  min-height: 100vh;
  background: #F5F7FA;
}

/* 缓存信息 */
.cache-info {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
}

.cache-text {
  font-size: 24rpx;
  color: #FFFFFF;
}

/* 筛选标签 */
.filter-tabs {
  display: flex;
  background: #FFFFFF;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #E5E5E5;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #666666;
  position: relative;
}

.tab-item.active {
  font-weight: 500;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  border-radius: 2rpx;
}

/* 优惠券列表 */
.coupon-list {
  padding: 24rpx 32rpx;
}

.coupon-item {
  display: flex;
  background: #FFFFFF;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.coupon-left {
  width: 200rpx;
  padding: 32rpx 24rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.coupon-left.available {
  color: #FFFFFF;
}

.coupon-left.used {
  background: #CCCCCC;
  color: #FFFFFF;
}

.coupon-left.expired {
  background: #FF6B6B;
  color: #FFFFFF;
}

.coupon-amount {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
}

.currency {
  font-size: 24rpx;
  margin-right: 4rpx;
}

.amount {
  font-size: 48rpx;
  font-weight: bold;
}

.discount-suffix {
  font-size: 28rpx;
  font-weight: 500;
  margin-left: 4rpx;
}

.coupon-condition {
  font-size: 22rpx;
  opacity: 0.9;
}

.coupon-right {
  flex: 1;
  padding: 32rpx 24rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.coupon-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 8rpx;
}

.coupon-desc {
  font-size: 26rpx;
  color: #666666;
  margin-bottom: 16rpx;
}

.coupon-time {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 16rpx;
}

.coupon-status {
  display: flex;
  justify-content: flex-end;
}

.status-text {
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
  border: 1rpx solid;
}

.status-text.available {
  /* 样式通过内联方式应用 */
}

.status-text.used {
  color: #CCCCCC;
  border-color: #CCCCCC;
  background: rgba(204, 204, 204, 0.1);
}

.status-text.expired {
  color: #FF6B6B;
  border-color: #FF6B6B;
  background: rgba(255, 107, 107, 0.1);
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
  margin-top: 16rpx;
}

/* 空状态 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 32rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 32rpx 0;
}

.load-more-text {
  font-size: 28rpx;
}

/* 线下核销按钮 */
.coupon-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.offline-verify-btn {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  margin-left: 16rpx;
}

.verify-btn-text {
  font-size: 24rpx;
  color: #FFFFFF;
  font-weight: 500;
}

/* 二维码弹窗样式 */
.qr-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.qr-modal-content {
  width: 600rpx;
  background: #FFFFFF;
  border-radius: 24rpx;
  overflow: hidden;
  animation: modalSlideUp 0.3s ease-out;
}

.qr-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #E5E5E5;
}

.qr-modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.qr-modal-close {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #F5F5F5;
}

.close-icon {
  font-size: 32rpx;
  color: #666666;
  line-height: 1;
}

.qr-modal-body {
  padding: 32rpx;
  text-align: center;
}

.coupon-info-card {
  background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 32rpx;
  color: #FFFFFF;
}

.coupon-name {
  font-size: 28rpx;
  font-weight: 600;
  margin-bottom: 16rpx;
}

.coupon-amount-display {
  display: flex;
  align-items: baseline;
  justify-content: center;
  margin-bottom: 12rpx;
}

.coupon-amount-display .currency {
  font-size: 24rpx;
  margin-right: 4rpx;
}

.coupon-amount-display .amount {
  font-size: 48rpx;
  font-weight: bold;
}

.coupon-amount-display .discount-suffix {
  font-size: 28rpx;
  font-weight: 500;
  margin-left: 4rpx;
}

.coupon-condition-text {
  font-size: 24rpx;
  opacity: 0.9;
}

.qr-code-container {
  display: flex;
  justify-content: center;
  margin-bottom: 24rpx;
}

.qr-canvas,
.qr-code-image {
  width: 300rpx;
  height: 300rpx;
  border: 1rpx solid #E5E5E5;
  border-radius: 12rpx;
}

.qr-code-text {
  background: #F8F9FA;
  padding: 16rpx 24rpx;
  border-radius: 12rpx;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-text-label {
  font-size: 26rpx;
  color: #666666;
  margin-right: 8rpx;
}

.qr-text-value {
  font-size: 26rpx;
  color: #333333;
  font-weight: 500;
  font-family: 'Courier New', monospace;
}

.qr-tips {
  padding: 16rpx;
}

.tips-text {
  font-size: 24rpx;
  color: #999999;
  line-height: 1.5;
}

/* 弹窗动画 */
@keyframes modalSlideUp {
  from {
    opacity: 0;
    transform: translateY(100rpx) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
</style>